package com.xxin.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.logging.log4j2.Log4j2Impl;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.session.Configuration;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.support.JdbcTransactionManager;
import org.springframework.transaction.TransactionManager;

import javax.sql.DataSource;
import javax.xml.crypto.Data;
import java.io.IOException;
import java.util.Properties;

/**
 * @author 小欣
 * @version 1.0
 * @since 1.8
 */
@PropertySource("classpath:jdbc.properties")
@MapperScan("com.xxin.mapper")
public class MybatisConfig {
	
	private static final Logger log = LogManager.getLogger(MybatisConfig.class);
	
	@Value("${jdbc.driver}")
	private String driver;
	@Value("${jdbc.url}")
	private String url;
	@Value("${jdbc.username}")
	private String username;
	@Value("${jdbc.password}")
	private String password;
	
	@Bean
	public DataSource dataSource(){
		DruidDataSource druidDataSource = new DruidDataSource();
		druidDataSource.setDriverClassName(driver);
		druidDataSource.setUrl(url);
		druidDataSource.setUsername(username);
		druidDataSource.setPassword(password);
		return druidDataSource;
	}
	
	@Bean
	public TransactionManager transactionManager(DataSource dataSource){
		JdbcTransactionManager jdbcTransactionManager = new JdbcTransactionManager();
		jdbcTransactionManager.setDataSource(dataSource);
		return jdbcTransactionManager;
	}
	
	@Bean
	public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		sqlSessionFactoryBean.setDataSource(dataSource);
		try {
			sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("/mapper/**/*.xml"));
		} catch (IOException e) {
			log.error(e.getMessage());
		}
//		setting配置
		Configuration configuration = new Configuration();
		configuration.setMapUnderscoreToCamelCase(true);
		configuration.setLogImpl(StdOutImpl.class);
		sqlSessionFactoryBean.setConfiguration(configuration);
//		插件配置
		PageInterceptor pageInterceptor = new PageInterceptor();
		Properties properties = new Properties();
		properties.setProperty("helperDialect","mysql");
		properties.setProperty("reasonable","true");
		pageInterceptor.setProperties(properties);
		sqlSessionFactoryBean.setPlugins(pageInterceptor);
		
		return sqlSessionFactoryBean;
	}
}
